/**
 * 
 */
package com.gr.notes.core.push;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;


/**
 * @author Graham Rhodes 20 Feb 2011 13:10:57
 */
public abstract class AbstractPushEventHandler<EventType> implements IPushEventHandler<EventType> {

    private static final long serialVersionUID = 1L;

    protected void appendHTML(final AjaxRequestTarget target, final Label component, final String html) {
        if (html == null)
            return;

        // update the component's model object for the case when the page is refreshed using F5
        component.setEscapeModelStrings(false);
        final IModel<?> model = component.getDefaultModel();
        if (model == null)
            component.setDefaultModelObject(html);
        else
            component.setDefaultModelObject(model.toString() + html);

        // escape backslashes for JavaScript
        final String escapedHTML = html.replaceAll("\\\\", "&#92;");

        target.appendJavascript("" + //
                "var target = document.getElementById('"
                + component.getMarkupId()
                + "');"
                + //
                "target.innerHTML += '"
                + escapedHTML
                + "';"
                + //
                "target.scrollTop = target.scrollHeight" //
        );
    }
}
